const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const utils = require('./util/utils')
const server = app.listen(utils.getServerPort(), function () {
    // let port = server.address().port;
    console.log("Example app listening at http://127.0.0.1:%s", utils.getServerPort())
});
app.use(express.static('public'));
app.use(cookieParser());
app.get('/', function (req, res) {
    res.end("HELLO,WORLD!");
});
var log4js = require('log4js');
log4js.configure('./config/log4js.json');

var log = log4js.getLogger("worker");

app.use(bodyParser.json());
app.post('/api', function (req, res) {
    try {
        let router = req.body.route;//http://127.0.0.1:8081/api?route=index
        if (!router) {
            res.end('参数不符合规定')
        }
        let leader = require("./routes/" + router);
        log.info(`请求地址为${router}`);
        leader.handle(req, res);
    } catch (e) {
        console.log(e)
    }
});
log.trace('Entering cheese testing');
log.debug('Got cheese.');
log.info('Cheese is Gouda.');
log.warn('Cheese is quite smelly.');
log.error('Cheese is too ripe!');
log.fatal('Cheese was breeding ground for listeria.');
app.get('/views', function (req, res) {
    let address = req.query.address;
    if (address) {
        res.sendFile("/public/views/" + address + ".html")
    } else {
        address = "index";
        res.sendFile("/public/views/" + address + ".html")
    }
    res.end();
});
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.post('/process_post', urlencodedParser, function (req, res) {
    response = {
        first_name: req.body.first_name,
        last_name: req.body.last_name,
    };
    log.info(response);
    res.end(JSON.stringify(response));
});
